﻿using DevExpress.Data.XtraReports.Native;
using DevExpress.Mvvm;
using DevExpress.Mvvm.Native;
using HandyControl.Controls;
using PlaceOrder_Core.Helper;
using PlaceOrder_Core.Services.Instances;
using PlaceOrder_Shared.ModelsToLily;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PlaceOrder_Client.ViewModels
{
    internal class ChatWorkOrderViewModel:Prism.Mvvm.BindableBase
    {
        #region 依赖属性
        private ObservableCollection<ChatWorkOrder> chatWorkOrders;

        public ObservableCollection<ChatWorkOrder> ChatWorkOrders
        {
            get { return chatWorkOrders; }
            set { chatWorkOrders = value;RaisePropertyChanged(); }
        }

        #endregion

        public DelegateCommand SearchCommand { get; set; }  
        public ChatWorkOrderViewModel()
        {
            InitCommand();
            InitValue();
        }

        private void InitCommand()
        {
            this.SearchCommand = new DelegateCommand(SearchHandle);
        }

        private async void InitValue()
        {
            // 创建一个 Stopwatch 实例
            Stopwatch stopwatch = new Stopwatch();

            // 开始计时
            stopwatch.Start();
            try
            {
               
                var tempVals = await UserHelper.GetChatWorkOrders();
                var tempVal = tempVals.Where(o => o.CreateBy == UserHelper.UserID);
                List<ChatWorkOrder> chatWorkOrders = new List<ChatWorkOrder>();
                if (tempVal != null && tempVal.Any())
                {
                    // 创建一个列表来存储异步任务
                    var tasks = new List<Task<ChatWorkOrder>>();

                    foreach (var lilyChatWorkOrder in tempVal)
                    {
                        // 创建异步任务来处理每个 ChatWorkOrder
                        tasks.Add(Task.Run(async () =>
                        {
                            ChatWorkOrder chatWorkOrder = new ChatWorkOrder();
                            chatWorkOrder.Status = lilyChatWorkOrder.Status;
                            chatWorkOrder.Remarks = lilyChatWorkOrder.Remarks;
                            chatWorkOrder.Type = (int)lilyChatWorkOrder.Type;
                            chatWorkOrder.ReviewBy = lilyChatWorkOrder.ReviewedBy;
                            chatWorkOrder.UpdateTime = lilyChatWorkOrder.UpdateTime;
                            chatWorkOrder.CreateTime = lilyChatWorkOrder.CreateTime;

                            string tradeIdsString = lilyChatWorkOrder.TradeIds;

                            // 使用 Split 方法将字符串拆分为数组，然后转换为 List<string>
                            List<string> tradeIdsList = tradeIdsString.Split(',')
                                                                      .Select(id => id.Trim()) // 去除每个 ID 的前后空白字符（如果有的话）
                                                                      .ToList();

                            // 将转换后的 List<string> 赋值给 chatWorkOrder.TradeIds
                            chatWorkOrder.TradeIds = tradeIdsList;
                            if (!string.IsNullOrEmpty(lilyChatWorkOrder.MessageId))
                            {
                                // 根据 MessageId 获取对应的 LilyChatMessage
                                LilyChatMessage chatMessage = await UserHelper.FindChatMessageByIdAsync(lilyChatWorkOrder.MessageId);

                                if (chatMessage != null)
                                {
                                    // 将获取到的 ChatMessage 填充到 ChatWorkOrder 中
                                    chatWorkOrder.ChatMessageInfo = chatMessage.ChatMessage;
                                }
                                else
                                {
                                    // 处理获取失败的情况
                                    chatWorkOrder.ChatMessageInfo = "";
                                }
                            }
                            else
                            {
                                chatWorkOrder.ChatMessageInfo = "";
                            }
                            return chatWorkOrder;
                        }));
                    }

                    // 等待所有任务完成
                    var chatWorkOrdersResults = await Task.WhenAll(tasks);

                    // 将结果转换为 ObservableCollection
                    this.ChatWorkOrders = new ObservableCollection<ChatWorkOrder>(chatWorkOrdersResults);
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError("查询审核单出错" + ex.Message + "---" + ex.StackTrace);
            }
            finally
            {
                // 停止计时
                stopwatch.Stop();

                // 输出耗时
                AppLog.WriteInfo($"查询审核单InitValue 方法耗时: {stopwatch.ElapsedMilliseconds} 毫秒");
                Growl.InfoGlobal($"查询审核单InitValue 方法耗时: {stopwatch.ElapsedMilliseconds} 毫秒");
            }
           
        }

        private void SearchHandle()
        {
            InitValue();
        }
    }
}
